package li;

import java.awt.*;
import java.awt.event.*;
import java.applet.*;


import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;


public class 计算器  extends Applet implements ActionListener{
	
	

	/**
	 * 
	 */
	TextField text=new TextField();
	StringBuffer str=new StringBuffer();
	public void init(){
		setLayout(new BorderLayout(5, 5));
		add(text,BorderLayout.NORTH);
		
		text.addActionListener(this);
		Panel pa=new Panel();
		pa.setLayout(new GridLayout(5,5,5,5));
		add(pa, BorderLayout.CENTER);
		String[] s1={"C","MC",".","1","2","3","4","5","6","7","8","9","0","(",")"};
		for(int i=0;i<s1.length;i++){
			Button btn=new Button(s1[i]);
			btn.addActionListener(this);
			pa.add(btn);	
		}
		
		Panel pa2=new Panel();
		pa2.setLayout(new GridLayout(5,1,5,5));
		add(pa2, BorderLayout.EAST);
		String[] s2={"+","-","*","/","="};
		for(int i=0;i<s2.length;i++){
			Button btn=new Button(s2[i]);
			btn.addActionListener(this);
			pa2.add(btn);
			
		}
		
		
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getActionCommand()=="="){
			
			
			try {
				if(str.length()!=0){
					ScriptEngine se = new ScriptEngineManager().getEngineByName("JavaScript");
					String d =  se.eval(str.toString()).toString();
					text.setText(d);
					str.delete(0, str.length());
				}
			} catch (ScriptException e1)
			{
				text.setText("������� ����������");
				str.delete(0, str.length());
			}	
			
		}else if(e.getActionCommand()=="C"){
			if(str.length()!=0){
				str.deleteCharAt(str.length()-1);
				text.setText(str.toString());
			}
		}else if(e.getActionCommand()=="MC"){
			str.delete(0, str.length());
			text.setText(str.toString());
		}else {
			
				str.append(e.getActionCommand());
				text.setText(str.toString());
		}
		
	}
}
